package com.example.socket.server;

import com.example.socket.executor.NettyMultithreadEventExecutorGroup;
import com.example.socket.thread.NamedThreadFactory;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.ExecutorService;

/**
 * 执行器配置信息<br/>
 * 用于创建一个受配置的{@link ExecutorFilter}
 * @author frank
 */
public class ExecutorConfig {
    public static int MAXIMUM_CAPACITY = 1 << 16;
    public static final String NAME = "executor";

    private int min;
    private int buffSize;
    private boolean customGroup;

    public static ExecutorConfig valueOf(int min, int buffSize, boolean costomGroup) {
        ExecutorConfig result = new ExecutorConfig();
        result.min = min;
        result.buffSize = calcSize(buffSize);
        result.customGroup = costomGroup;
        return result;
    }

    public static int calcSize(int n) {
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    /**
     * 创建 {@link EventExecutorGroup} 并返回
     * @return
     */
    public ExecutorService build() {
        ThreadGroup group = new ThreadGroup("通信模块");
        NamedThreadFactory threadFactory = new NamedThreadFactory(group, "通信线程");
        if (customGroup) {
            return new NettyMultithreadEventExecutorGroup(min, threadFactory, buffSize);
        }
        return new DefaultEventExecutorGroup(min, threadFactory);
    }

    // Getter and Setter ...

    public int getMin() {
        return min;
    }

    public int getBuffSize() {
        return buffSize;
    }

    public boolean isCustomGroup() {
        return customGroup;
    }
}